<template>
  <div id="app">
    <input type="text" v-model="msg" @keypress.enter="send" />
    <button type="button" @click="send">点击</button>
  </div>
</template>
<script>
export default {
  data () {
    return {
      wsInstance: undefined,
      msg: ''
    }
  },
  methods: {
    init () {
      return new Promise((resolve, reject) => {
        this.$ws('localhost:8765').then((ws) => {
          this.wsInstance = ws

          resolve(ws)

          ws.onclose = (e) => {
            this.wsInstance = undefined
          }
        })
      }).catch((err) => {
        reject(err)
      })
    },
    checkWs () {
      return new Promise((resolve, reject) => {
        if (this.wsInstance) {
          resolve()
        } else {
          console.warn('ws失去连接 重连中。。。')
          this.init()
            .then(() => {
              resolve()
            })
            .catch(() => {
              console.error('ws重连失败')
              reject()
            })
        }
      })
    },
    send () {
      this.checkWs()
        .then(() => {
          this.wsInstance.send(
            JSON.stringify({
              type: this.msg
            })
          )
        })
        .catch(() => {
          console.error('ws发送失败')
        })
    }
  },
  created () {
    this.init()
  }
}
</script>
<style lang="stylus"></style>
